#include "../http/HttpServer.h"
#include "../curl/CurlClient.h"
#include "../http/HttpData.h"
#include "../common/global.h"
#include "../common/CCReactor.h"
#include <iostream>
#include <thread>
#include <chrono>

int main() {
    std::cout << "=== Simple Server-Client Test ===" << std::endl;
    
    try {
        // Initialize reactor
        g_reactor->Init();
        g_reactor->Start();
        
        std::cout << "Reactor initialized" << std::endl;
        
        // Create server
        HttpServer server;
        
        // Set up simple handler
        auto handler = [&server](uint32_t handle, stHttpRequest&& req) -> int {
            std::cout << "Server received request: " << req.method << " " << req.url << std::endl;
            
            // Create simple response
            stHttpResponse resp;
            resp.state = 200;
            resp.heads["Content-Type"] = "application/json";
            resp.heads["Server"] = "SimpleServer/1.0";
            resp.body = "{\"status\": \"ok\", \"message\": \"Hello from server!\"}";
            
            // Send response
            server.Response(handle, std::move(resp));
            return 0;
        };
        
        // Start server
        int result = server.Start("127.0.0.1", 8084, handler);
        if (result != 0) {
            std::cout << "Failed to start server" << std::endl;
            return 1;
        }
        
        std::cout << "Server started on http://127.0.0.1:8084" << std::endl;
        
        // Give server time to start
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        
        // Test client
        std::cout << "Testing client..." << std::endl;
        CurlClient client;
        if (!client.Initialize()) {
            std::cout << "Failed to initialize client" << std::endl;
            return 1;
        }
        
        stHttpRequest req;
        req.method = "GET";
        req.url = "http://127.0.0.1:8084/test";
        req.heads["User-Agent"] = "SimpleTest/1.0";
        
        stHttpResponse resp;
        result = client.Request(std::move(req), resp);
        
        std::cout << "Client request completed: " << result << std::endl;
        if (result == 0) {
            std::cout << "Response status: " << resp.state << std::endl;
            std::cout << "Response body: " << resp.body << std::endl;
        }
        
        // Clean up
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        g_reactor->Stop();
        
        std::cout << "Test completed successfully!" << std::endl;
        
    } catch (const std::exception& e) {
        std::cout << "Test failed with exception: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}